package main

import (
	"errors"
	"fmt"
	"log"

	"gorm.io/gorm"
	"gorm.io/gorm/logger"

	"gitee.com/general252/kingbase-gorm-pgx"
)

type Student struct {
	UID   string `gorm:"'uid' not null unique VARCHAR(64)"`
	Name  string
	Age   int
	Index int
	DevId string `gorm:"column:dev_id;type:string;default:'';size:64;uniqueIndex:udx_dev_id;not null"` // 设备Id
}

func init() {
	log.SetFlags(log.LstdFlags | log.Lshortfile)
}

func main() {

	const (
		host     = "192.168.88.88"
		port     = 54321
		user     = "system"
		password = "123456"
		dbname   = "test"
	)

	dsn := fmt.Sprintf("kingbase://%v:%v@%v:%v/%v?sslmode=disable", user, password, host, port, dbname)
	config := kingbase_gorm_pgx.Config{
		DriverName: "kingbase",
		DSN:        dsn,
	}

	db, err := gorm.Open(kingbase_gorm_pgx.New(config), &gorm.Config{})
	if err != nil {
		log.Println(err)
		return
	}

	db.Logger = db.Logger.LogMode(logger.Info)

	if true {
		if err = db.AutoMigrate(new(Student)); err != nil {
			log.Println("表同步失败", err)
			return
		} else {
			log.Println("表同步成功")
		}
	}

	var value Student
	if tx := db.First(&value); tx.Error != nil {
		if !errors.Is(tx.Error, gorm.ErrRecordNotFound) {
			log.Println(err)
			return
		}
	}

	log.Printf("%#v", value)
}
